package mspbots.teams.client.core.data.apps;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.log4j.Log4j2;
import mspbots.teams.client.core.AbstractToolsUtil;
import mspbots.teams.client.oauth.TokenState;
import mspbots.teams.common.QueryParams;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.Map;

/**
 * mspbots.data.teams.core.groups.GroupsService
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2020/6/3
 */
@Log4j2
@Service
public class AppsServiceImpl extends AbstractToolsUtil {

    public Flux<JsonNode> find(TokenState state) {
        return this.get()
                .contextWrite(ctx -> ctx.put("tokenState", state));
    }

    private Flux<JsonNode> get() {
        return this.getMeGroups()
                .delayElements(Duration.ofSeconds(1))
                .flatMap(jsonNode -> this.teamsClient.get("/v1.0/teams/{groupId}/installedApps",
                        QueryParams.withDefault().setExpand("teamsAppDefinition"),
                        Map.of("groupId", jsonNode.get("id").textValue()))
                        .onErrorResume(err -> {
                            log.debug("Get installed apps [{}] installed apps, err msg: {}",
                                    jsonNode.get("id").textValue(), err.getMessage());
                            return Mono.empty();
                        }))
                .flatMap(jsonNode -> Flux.fromIterable(jsonNode.withArray("value")));
    }

    private Flux<JsonNode> getMeGroups() {
        return this.teamsClient.get("v1.0/me/joinedTeams", QueryParams.withDefault().setSelect("id"), Map.of())
                .flatMapMany(resultNode -> Flux.fromIterable(resultNode.withArray("value")));
    }


}
